package com.link.base.base.report.service;

import com.link.base.basic.dao.mybatis.mapper.BasicCommonMapper;
import com.link.base.basic.model.ListOfValue;
import com.link.base.user.model.CoreUser;
import com.link.base.base.consumer.util.poi.PoiUtil;
import com.link.base.base.report.dao.mybatis.mapper.PortalReportMapper;
import com.link.base.base.report.model.*;
import com.link.base.base.system.service.PeriodService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import com.link.base.base.report.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 * @comments 报表
 */
@Component
public class PortalReportServiceImpl implements PortalReportService {
    @Resource
    private PortalReportMapper portalReportMapper;

    @Resource
    private BasicCommonMapper basicCommonMapper;

    @Resource
    private PeriodService periodService;

    public static void main(String[] args) {
//      getDayStartTimeMillis(-27);
        getCustomDayByString("2000-02-29", 0);
    }

    /**
     * 返回年的起始时间，参数为权值，0默认为本年
     *
     * @param plusYear
     * @return
     */
    private static long getYearStartTimeMillis(int plusYear) {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), 0, 1, 0, 0, 0);
        cal.add(Calendar.YEAR, plusYear);
        return cal.getTimeInMillis();
    }

    /**
     * 返回月的起始时间，参数为权值，0默认为本月
     *
     * @param monthPlus
     * @return
     */
    private static long getMonthStartTimeMillis(int monthPlus) {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
        cal.add(Calendar.MONTH, monthPlus);
        return cal.getTimeInMillis();
    }

    /**
     * 返回天的起始时间，参数为权值，0默认为今天
     *
     * @return
     */
    private static long getDayStartTimeMillis(int dayPlus) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DAY_OF_MONTH, dayPlus);
        return cal.getTimeInMillis();
    }

    /**
     * 根据传入字符串日期yyyy-mm-dd返回对应的long
     *
     * @param datetime
     * @param dayPlus  ：日期加权
     * @return
     */
    private static long getCustomDayByString(String datetime, int dayPlus) {
        if (!PoiUtil.valiDateWithLongFormat(datetime) || StringUtils.isBlank(datetime)) {
            throw new ServiceException("PUBLIC-061");
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        long temp = new Long("9999999999999999");
        try {
            temp = sf.parse(datetime).getTime();
        } catch (ParseException e) {
            LCLogger.withException(e);
            throw new ServiceException("PUBLIC-061");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(temp);
        cal.add(Calendar.DAY_OF_MONTH, dayPlus);
        return cal.getTimeInMillis();
    }

    /**
     * 商机阶段-销售漏斗
     */
    @Override
    public List<PortalOptyStageReport> queryOptyStageReport(PortalSearchText params) throws Exception {
        return portalReportMapper.queryOptyStageReport(params);
    }

    @Override
    public List<PortalBaseDataReport> queryReport(PortalReportSearch rs) throws Exception {
        return portalReportMapper.queryReport(rs);

    }

    /**
     * 客户类型报表
     */
    @Override
    public List<PortalAccountTypeReport> queryAccntTypeReport(PortalAccountTypeReport acctTypeReport) throws Exception {


        return portalReportMapper.queryAccntTypeReportSelect(acctTypeReport);
    }

    /**
     * 根据销售负责人统计客户类型报表
     */
    @Override
    public List<PortalAccountTypeReport> queryAccntTypeReportByPostn(PortalAccountTypeReport acctTypeReport) throws Exception {
        acctTypeReport.setPostnId(UserUtil.getUser().getPostnId());
        return portalReportMapper.queryAccntTypeReportByPostn(acctTypeReport);
    }

    @Override
    public List<PortalOptyTop10Report> queryOptyTop10Report(PortalOptyTop10Report optyTop10Report) throws Exception {

        return portalReportMapper.queryOptyTop10ReportSelect(optyTop10Report);
    }

    @Override
    public List<PortalSalesAmount> querySalesAmountReport(PortalSalesAmount salesAmount) throws Exception {
        CoreUser user = UserUtil.getUser();
        salesAmount.setCreatedBy(user.getId());
        salesAmount.setCorpid(user.getCorpid());
        return portalReportMapper.querySalesAmountReportSelect(salesAmount);
    }

    @Override
    public List<PortalSalesAmount> queryYearPeriodSales(PortalSalesAmount salesAmount) throws Exception {
        CoreUser user = UserUtil.getUser();
        Long corpId = user.getId();
        salesAmount.setCorpid(corpId);
        Long postnId = user.getPostnId();
        salesAmount.setPostnId(postnId);

        return portalReportMapper.queryYearPeriodSales(salesAmount);
    }


    @Override
    public List<PortalProductSalesReport> queryProductSalesReport(PortalProductSalesReport prodSalesReport)
            throws Exception {
        prodSalesReport.setCreatedBy(UserUtil.getUser().getId());
        return portalReportMapper.queryProductSalesReportSelect(prodSalesReport);
    }

    @Override
    public List<PortalConsumerSourceConstitute> queryConsumerSourceConstitute(PortalConsumerSourceConstitute record) throws Exception {
        //查询消费者来源类型和其对应的数量
        List<PortalConsumerSourceConstitute> reportList = portalReportMapper.queryConsumerSourceConstitute(record);
        //从值列表中查出当前消费者来源的类型
        ListOfValue lovParam = new ListOfValue();
        lovParam.setType("ACCT_CHANNEL");
        lovParam.setActiveFlag("Y");
        List<ListOfValue> lovList = basicCommonMapper.queryAll(lovParam);

        //将来源类型对应的显示值写入
        // 设置一个flag，标识值列表中的某个值不在查出的结果集中
        boolean nullFlag = false;
        for (ListOfValue lov : lovList) {
            for (int i = 0; i < reportList.size(); i++) {
                if (lov.getVal().equals(reportList.get(i).getAcctChannel())) {
                    nullFlag = true;
                    //将值列表的显示值写入结果集
                    reportList.get(i).setAcctChannelName(lov.getName());
                }
                if (null == reportList.get(i).getAcctChannel()) {
                    //如果结果集存在来源渠道为空的数据，将其独立源代码和显示值赋为 Unknown 和 未知
                    reportList.get(i).setAcctChannel("Unknown");
                    reportList.get(i).setAcctChannelName("未知");
                }
            }
            if (!nullFlag) {
                //如果结果集中不含有该独立源代码，新建一个list成员，并将其赋值，数量为0
                PortalConsumerSourceConstitute entity = new PortalConsumerSourceConstitute();
                entity.setAcctChannel(lov.getVal());
                entity.setAcctChannelName(lov.getName());
                entity.setNum(0);
                reportList.add(entity);
            }
            nullFlag = false;
        }
        return reportList;
    }

    @Override
    public Map<String, Object> queryConsumerSourceGrowth(PortalConsumerSourceConstitute record) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        //当变量“最近”数量大于0时才做报表的查询
        if (record.getLatelyNum() > 0) {
            Date startDate;
            Date endDate;
            //查询最近latelyNum年的数据
            String year = "year";
            if (year.equals(record.getConsumerGrowthType())) {
                for (int i = 1; i <= record.getLatelyNum(); i++) {
                    startDate = new Date(getYearStartTimeMillis(i - record.getLatelyNum()));
                    endDate = new Date(getYearStartTimeMillis(i - record.getLatelyNum() + 1));
                    record.setStartDate(startDate);
                    record.setEndDate(endDate);
                    List<PortalConsumerSourceConstitute> list = queryConsumerSourceConstitute(record);
//                  result.put(String.valueOf(cal.get(Calendar.YEAR) - record.getLatelyNum() + i) + "年", list);
                    result.put(String.valueOf(i - 1), list);
                }
            }
            //查询最近latelyNum月的数据
            String month = "month";
            if (month.equals(record.getConsumerGrowthType())) {
                for (int i = 1; i <= record.getLatelyNum(); i++) {
                    startDate = new Date(getMonthStartTimeMillis(i - record.getLatelyNum()));
                    endDate = new Date(getMonthStartTimeMillis(i - record.getLatelyNum() + 1));
                    record.setStartDate(startDate);
                    record.setEndDate(endDate);
                    List<PortalConsumerSourceConstitute> list = queryConsumerSourceConstitute(record);
                    result.put(String.valueOf(i - 1), list);
                }
            }
            //查询最近latelyNum天的数据
            String day = "day";
            if (day.equals(record.getConsumerGrowthType())) {
                for (int i = 1; i <= record.getLatelyNum(); i++) {
                    startDate = new Date(getDayStartTimeMillis(i - record.getLatelyNum()));
                    endDate = new Date(getDayStartTimeMillis(i - record.getLatelyNum() + 1));
                    record.setStartDate(startDate);
                    record.setEndDate(endDate);
                    List<PortalConsumerSourceConstitute> list = queryConsumerSourceConstitute(record);
                    result.put(String.valueOf(i - 1), list);
                }
            }
            //查询最近最近N天的总数据
            String sumDay = "sumDay";
            if (sumDay.equals(record.getConsumerGrowthType())) {
                int startDay = 1 - record.getLatelyNum();
                startDate = new Date(getDayStartTimeMillis(startDay));
                endDate = new Date(getDayStartTimeMillis(1));
                record.setStartDate(startDate);
                record.setEndDate(endDate);
                List<PortalConsumerSourceConstitute> list = queryConsumerSourceConstitute(record);
                result.put("0", list);
            }
            //查询自定义日期范围
            String customDay = "customDay";
            if (customDay.equals(record.getConsumerGrowthType())) {
                startDate = new Date(getCustomDayByString(record.getStartDateParam(), 0));
                endDate = new Date(getCustomDayByString(record.getEndDateParam(), 1));
                record.setStartDate(startDate);
                record.setEndDate(endDate);
                List<PortalConsumerSourceConstitute> list = queryConsumerSourceConstitute(record);
                result.put("0", list);
            }
        }
        return result;
    }
}
